import React, { useContext, useEffect, useState } from 'react';
import {
  Button,
  Form,
  Grid,
  Input,
  Message,
  Modal,
  Select,
  Space,
  Switch,
  Typography,
} from '@arco-design/web-react';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import { GlobalContext } from '@/context';
import styles from './style//index.module.less';
import { EnumsRes } from '@/api/interface';
import { entityGet } from '@/api/modules/entity';
import { entityProfilesCreate } from '@/api/interface/entityProfiles';
import { Emirates } from '@/api/modules';
import { Create, Update } from '@/api/modules/entityProfiles';
import useIsMountedRef from '@/utils/useIsMountedRef';
import ModalTitle from '@/components/ModalTitle';
import cs from 'classnames';

const Option = Select.Option;
const TextArea = Input.TextArea;
const { Title } = Typography;
const { Row, Col } = Grid;
const { useForm } = Form;

const handleInputChange = (event) => {
  const { value } = event.target;
  event.target.value = value.trim().replace(/[^0-9]/g, '');
};

function CreateForm({
  record,
  visible,
  onVisible,
}: {
  record: entityProfilesCreate;
  visible: boolean;
  onVisible: (status: boolean, refresh?: boolean) => void;
}) {
  const t = useLocale(locale);
  const { lang, rtl } = useContext(GlobalContext);
  const [form] = useForm();
  const [loading, setLoading] = useState(false);

  const [emirate, setEmirate] = useState<Array<EnumsRes>>([]);
  const getEmirate = () => {
    Emirates()
      .then((res) => {
        if (isMountedRef.current) {
          setEmirate(res.data);
        }
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const [entitys, setEntitys] = useState([]);
  const getEntitys = (e) => {
    if (!e) {
      setEntitys([]);
      form.setFieldsValue({
        entityId: undefined,
      });
      return;
    }
    entityGet({ emirate: e, active: true })
      .then((res) => {
        setEntitys(() => [...res.data]);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    getEmirate();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const [formParams, setFormParams] = useState<entityProfilesCreate>({
    id: '',
    admin: false,
    active: true,
  });

  useEffect(() => {
    if (visible) {
      setLoading(false);
      if (record.id) {
        setFormParams(() => ({
          id: record.id,
          admin: Boolean(record.admin),
          active: record.active,
        }));
        if (record.emirate && record.emirate.key) {
          getEntitys(record.emirate.key);
        }
        form.setFieldsValue({
          admin: Boolean(record.admin),
          email: record.email,
          emirate: record.emirate && record.emirate.key,
          entityId: (record.entity && record.entity.id) || undefined,
          jobDescription: record.jobDescription,
          mobile: record.mobile,
          officerName: record.officerName,
          officerNameAr: record.officerNameAr,
          officerNumber: record.officerNumber,
        });

        return;
      }
      console.log(888);
      setFormParams(() => ({
        id: '',
        admin: false,
        active: true,
      }));
      setEntitys([]);
      form.setFieldsValue({
        admin: false,
        entityId: undefined,
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);

  const onCreate = () => {
    form.validate((errors, values) => {
      if (!errors) {
        setLoading(true);
        if (record.id) {
          Update({ ...values, id: record.id, active: formParams.active })
            .then(() => {
              onVisible(false, true);
              form.resetFields();
              setLoading(false);
              Message.success(t['update.success']);
            })
            .catch(() => {
              setLoading(false);
            });
          return;
        }

        Create({ ...values, active: formParams.active })
          .then(() => {
            onVisible(false, true);
            form.resetFields();
            setLoading(false);
            Message.success(t['create.success']);
          })
          .catch(() => {
            setLoading(false);
          });
      }
    });
  };

  const onCancel = () => {
    form.resetFields();
    onVisible(false);
  };

  return (
    <div>
      <Modal
        title={
          <ModalTitle
            title={formParams.id ? t['create.editTitile'] : t['create.title']}
          />
        }
        style={{ width: '786px' }}
        visible={visible}
        onCancel={() => onCancel()}
        maskClosable={false}
        unmountOnExit={false}
        footer={null}
        className={cs(rtl ? 'rtl' : '')}
      >
        <div>
          <Form
            form={form}
            labelAlign="left"
            labelCol={{ span: 9 }}
            wrapperCol={{ span: 15 }}
            initialValues={formParams}
            validateMessages={{
              required: () => t['empty'],
            }}
            validateTrigger="onBlur"
            layout="vertical"
            autoComplete="off"
          >
            <Row gutter={24}>
              <Col span={24}>
                <Title heading={6} className={cs(rtl && 'text-right')}>
                  {t['create.personal']}
                </Title>
              </Col>

              <Col span={12}>
                <Form.Item
                  label={t['create.fullName']}
                  field="officerName"
                  rules={[{ required: true }]}
                >
                  <Input
                    allowClear
                    autoComplete="off"
                    maxLength={100}
                    placeholder={t['create.fullName.placeholder']}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.fullNameAr']}
                  field="officerNameAr"
                  rules={[{ required: true }]}
                >
                  <Input
                    allowClear
                    maxLength={100}
                    autoComplete="off"
                    placeholder={t['create.fullNameAr.placeholder']}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.mobile']}
                  field="mobile"
                  rules={[
                    { required: true },
                    {
                      validator: (val, cb) => {
                        if (!/^05\d{8}$/.test(val)) {
                          cb(t['create.mobile.message']);
                        }
                        if (val.length != 10) {
                          cb(t['create.mobile.message1']);
                        }
                        cb();
                      },
                    },
                  ]}
                >
                  <Input
                    autoComplete="off"
                    allowClear
                    maxLength={10}
                    placeholder={t['create.mobile.placeholder']}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.email']}
                  field="email"
                  rules={[
                    { required: true },
                    {
                      validator: (val, cb) => {
                        if (!val) {
                          cb();
                        }
                        if (
                          !/[\w]+(?:\.[\w]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/.test(
                            val
                          )
                        ) {
                          cb(t['create.email.message']);
                        }
                        // if (/[^A-Za-z0-9!#$%&'*+/=?^_`{|}~.-]/.test(val)) {
                        //   cb(t['create.email.message']);
                        // }
                        // 判断是否是私人邮箱
                        const personalEmailDomains = [
                          'gmail.com',
                          'outlook.com',
                          'yahoo.com',
                          'icloud.com',
                          'protonmail.com',
                          'aol.com',
                          'gmx.com',
                          'zoho.com',
                          'outlook.com',
                          'hotmail.com',
                          'mail.com',
                          'gmx.com',
                          'yandex.com',
                          'naver.com',
                          'daum.net',
                          'tuta.com',
                        ];
                        const domain = val.split('@')[1];
                        if (
                          personalEmailDomains.includes(domain.toLowerCase())
                        ) {
                          cb(t['create.email.message1']);
                        }
                        cb();
                      },
                    },
                  ]}
                >
                  <Input
                    autoComplete="off"
                    disabled={!!record.id}
                    allowClear
                    maxLength={100}
                    placeholder={t['create.email.placeholder']}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.jobDesc']}
                  field="jobDescription"
                  rules={[{ required: true }]}
                >
                  <Input
                    autoComplete="off"
                    maxLength={100}
                    allowClear
                    placeholder={t['create.jobDesc.placeholder']}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.officerNumber']}
                  field="officerNumber"
                  rules={[
                    { required: true },
                    {
                      validator: (val, cb) => {
                        if (!/^\d{9,12}$/.test(val)) {
                          cb(t['create.officerNumber.message']);
                        }
                        cb();
                      },
                    },
                  ]}
                >
                  <Input
                    autoComplete="off"
                    allowClear
                    onInput={handleInputChange}
                    maxLength={12}
                    placeholder={t['create.officerNumber.placeholder']}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.admin']}
                  field="admin"
                  rules={[{ required: true }]}
                >
                  <Switch
                    key={formParams.admin.toString() + visible.toString()}
                    defaultChecked={formParams.admin}
                  />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Title heading={6} className={cs(rtl && 'text-right')}>
                  {t['create.entityDetails']}{' '}
                </Title>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.emirate']}
                  field="emirate"
                  rules={[{ required: true }]}
                >
                  <Select
                    allowClear
                    placeholder={t['create.emirate.placeholder']}
                    onChange={getEntitys}
                  >
                    {emirate.map((option, index) => (
                      <Option key={index} value={option.key}>
                        {option.value[lang === 'en-US' ? 'en' : 'ar']}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.entityName']}
                  field="entityId"
                  rules={[{ required: true }]}
                >
                  <Select
                    showSearch
                    allowClear
                    placeholder={t['create.entityName.placeholder']}
                    triggerProps={{
                      autoAlignPopupWidth: false,
                      autoAlignPopupMinWidth: true,
                    }}
                    filterOption={(inputValue, option) => {
                      return (
                        option.props.children.props.children[0].props.children[0]
                          .toLowerCase()
                          .indexOf(inputValue.toLowerCase()) >= 0
                      );
                    }}
                  >
                    {entitys.map((option, index) => (
                      <Option key={index} value={option?.id}>
                        <div
                          style={{ display: 'flex' }}
                          className={rtl ? 'rtl' : 'ltr'}
                        >
                          <div>
                            {option[lang === 'en-US' ? 'name' : 'nameAr']},
                            {t['ShareholdingPercentage']}
                          </div>
                          {option.shareholdingPercentage && (
                            <>
                              (
                              <div
                                className={cs('ltr', rtl ? 'Cairo' : '')}
                                style={{ display: 'flex' }}
                              >
                                {option.shareholdingPercentage}
                                <div>%</div>
                              </div>
                              )
                            </>
                          )}
                        </div>
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Space size={24} className={styles['create-button-group']}>
                  <Button
                    type="outline"
                    size="large"
                    onClick={() => onCancel()}
                  >
                    {t['cancel']}
                  </Button>
                  <Button
                    type="primary"
                    size="large"
                    onClick={onCreate}
                    loading={loading}
                    loadingFixedWidth
                  >
                    {formParams.id ? t['save'] : t['add']}
                  </Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </Modal>
    </div>
  );
}

export default CreateForm;
